
physics:setGravity(0, -25)

local dw = director.displayWidth
local dh = director.displayHeight
local x = 150
local y = 150
local angle = 0
local ballMove = false
local forceX = 0
local forceY = 0
local posBallX = x
local posBallY = y
local touchBall = false

local ball = director:createSprite( {name="ball", x=x, y=y, source="img/paperBall.png",	xAnchor=0.5, yAnchor=0.5, zOrder =1} )
local basket = director:createSprite( {name="ball", x=500, y=100, source="img/basketFront.png",	xAnchor=0.5, yAnchor=1, zOrder=2} )
--local basketBack = director:createSprite( {name="ball", x=basket.x, y=basket.y, source="img/basketBack.png",	xAnchor=0.5, yAnchor=.5, zOrder=0} )
physics:addNode(basket, { type="static", isSensor=false } )

function basketCollition(event)
    local target = event.target
	if event.phase == "began" then
		dbg.print("Collision")
		if (ball.x > basket.x-basket.w/2 and ball.x < basket.x+basket.w/2) then
		else
			if (ball.x < basket.x) then
				if (ball.y > basket.y) then
					ball.physics:applyLinearImpulse(-1, 1)
				else
					ball.physics:applyLinearImpulse(-1, 0)
				end
			elseif (ball.x > basket.x) then
				ball.physics:applyLinearImpulse(1, 1)
			end
		end
	end
end
basket:addEventListener("collision", basketCollition)

local ballUpdate = function ()
	if  (ballMove == true) then
		if (ball.y-ball.w/2 < 0) then
			physics:removeNode(ball)
			physics:addNode(ball, { radius=ball.w/2, type="static", isSensor=false } )
		end
	 end
end
system:addEventListener("update", ballUpdate)

function ball:touch(event)
	if (event.phase == "began") then 
		posBallX = ball.x
		posBallY = ball.y
		touchBall = true
	end
end
ball:addEventListener("touch", ball)

local onTouch = function(event)
	if (event.phase == "moved") then
		if (touchBall == true) then
			x = event.x
			y = event.y
			angle = math.atan((posBallX-x)/(posBallY-y))*180/math.pi
			ball.rotation = angle
			if (ballMove == false) then
				if (ball.x < posBallX-ball.w*2) then
					ball.x = posBallX-ball.w*2
				elseif (ball.x > posBallX+ball.w*2) then
					ball.x = posBallX+ball.w*2
				else
					ball.x = x
				end
				if (ball.y < posBallY-ball.h*2) then
					ball.y = posBallY-ball.h*2
				elseif (ball.y > posBallY+ball.h*2) then
					ball.y = posBallY+ball.h*2
				else
					ball.y = y
				end
			end
	   end
	end
	if (event.phase == "ended") then 
		if (ballMove == false and touchBall == true) then
			ballMove = true
			physics:addNode(ball, { radius=ball.w/2, type="dynamic", isSensor=false } )
			forceX = (posBallX - x)*8
			forceY = (posBallY - y)*7
			ball.physics:applyForce (forceX, forceY, ball.x,ball.y)
		end
		touchball = false
	end
end
system:addEventListener("touch", onTouch)